<template>
  <div class="file-upload-content">
    <el-upload
      drag
      :action="action"
      :file-list="fileList"
      multiple
      ref="uploadRef"
      :on-success="uploadSuccess"
      :on-remove="fileRemove"
      :before-upload="validator"
    >
      <div class="upload-content">
        <i class="el-icon-upload" />
        <div>将文件拖到此处，或<span>点击上传</span></div>
        <p>
          <span>支持扩展名：</span
          ><i v-for="i in acceptFormat" :key="i">{{ i }}</i>
        </p>
      </div>
    </el-upload>
  </div>
  <div class="public">
    <span>保存位置：</span>
    <el-radio-group v-model="isPublic">
      <el-radio :label="0">个人库</el-radio>
      <el-radio :label="1" v-show="isRadio">公共库</el-radio>
    </el-radio-group>
  </div>
  <div>
    <h3>已选择章节：{{ knowledgeList.length }}章</h3>
    <div class="tag-box">
      <el-tag size="mini" v-for="o in knowledgeList" :key="o.id">{{
        o.name
      }}</el-tag>
    </div>
  </div>
</template>
<script lang="ts">
import { ref, Ref, PropType, nextTick } from "vue";
import $ from "$";
import { useStore } from "vuex";
import { ElMessage } from "element-plus";

export default {
  props: {
    isRadio: {
      type: Boolean
    },
    files: {
      type: Array as PropType<File[]>,
      default: () => [],
    },
    knowledgeList: {
      type: Array as PropType<any[]>,
      default: () => [],
    },
    type: Number,
  },
  setup(props) {
    let store = useStore();
    let uploadRef = ref();
    let action = `${import.meta.env.VITE_APP_BASE_URL}/system/file/uploadFile`;
    let acceptFormat = props.type === 5 ? [ 'doc', 'docx' ] : props.type === 6 ? ['mp3', 'mp4'] :  props.type === 1 ? ['zip']
      : [ 'ppt', 'pptx', 'doc', 'docx', 'pdf', 'mp4', 'mp3', 'jpg', 'png', 'jpeg', 'zip', 'rar' ];
    let nodes = ref([{ label: '讲义名称', type: 'input', key: 'name' }]);

    let subjectCode = store.getters.subject.code;

    let fileList: Ref<any[]> = ref([]);

    let files = [];
    if (files.length) {
      fileList.value = files.map((file: any) => ({
        name: file.name,
        status: "ready",
      }));
      Promise.all(
        props.files.map((file) => {
          let formdata = new FormData();
          formdata.append("file", file);
          return $.http.upload("/system/file/uploadFile", formdata);
        })
      ).then((list: any[]) => {
        list.map((res) => {
          fileList.value.splice(
            fileList.value.findIndex((f) => f.name === res.json.oriFilename),
            1,
            { ...res.json, name: res.json.oriFilename, url: res.json.filePath }
          );
        });
      });
    } else {
      nextTick(() => {
        const uploadDom: any = document.getElementsByClassName('el-upload__input');
        uploadDom[0].click();
      });
    }
    let validatorFiles: Ref<any[]> = ref([]);
    const validator = (file) => {
      let idx = file.name.lastIndexOf(".");
      let ext = file.name.substr(idx + 1).toLocaleLowerCase();
      let valid = acceptFormat.includes(ext);
      !valid &&
        ElMessage.warning(`请上传以下指定格式文件，${acceptFormat.join("、")}`);
      validatorFiles.value.push({ name: file.name, status: "ready" });
      return valid;
    };
    const uploadSuccess = (res, file, files) => {
      if (res.result) {
        validatorFiles.value.splice(
          validatorFiles.value.findIndex( (f) => f.name === res.json.oriFilename ),
          1,
          {
            ...res.json,
            name: res.json.oriFilename,
            url: res.json.filePath,
            status: file.status,
          }
        );
      }
    };
    const fileRemove = (file) => {
      fileList.value.splice(
        fileList.value.findIndex((f) => file.filePath === f.filePath),
        1
      );
    };

    let isPublic = ref(1);

    const save = (resolve, reject) => {
      if (!validatorFiles.value.every((file) => file.status === "success")) {
        ElMessage.warning("文件正在上传中.... 请稍等片刻~！");
        reject();
      } else if (validatorFiles.value.length) {
        fileList.value = validatorFiles.value;
        $.http
          .json("/admin/material/batchSave", {
            chapterId: props.knowledgeList.map((i) => i.id),
            isPublic: isPublic.value,
            subject: subjectCode,
            type: props.type,
            fileList: fileList.value,
          })
          .then((res: any) => {
            res.result ? resolve(res) : reject(ElMessage.error(res.msg));
          });
      } else {
        ElMessage.warning("请上传文件！");
        reject();
      }
    };

    return {
      action,
      save,
      uploadRef,
      fileList,
      uploadSuccess,
      fileRemove,
      isPublic,
      acceptFormat,
      validator,
      validatorFiles,
      nodes,
    };
  },
};
</script>
<style lang="scss" scoped>
:deep(.el-upload) {
  width: 100%;
  .el-upload-dragger {
    width: 100%;
    height: 180px;
    background: #f6f7f9;
  }
}
.upload-content {
  & > i {
    margin-top: 24px;
    color: #72b22a;
  }
  div {
    color: #1a2633;
    margin-bottom: 8px;
    span {
      color: #72b22a;
    }
  }
  p {
    color: #999;
    font-size: 12px;
    padding: 0 50px;
    i::after {
      content: "、";
      display: inline-block;
    }
  }
}
h3 {
  margin: 20px 0 10px;
}
:deep(.tag-box) {
  .el-tag {
    margin: 0 10px 10px 0;
  }
}
.public {
  margin: 20px 0;
  span {
    margin-right: 10px;
  }
}
</style>
